package com.bosssoft.trainee.nontax.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bosssoft.trainee.nontax.entity.dto.UserDTO;
import com.bosssoft.trainee.nontax.entity.po.UserPO;
import com.bosssoft.trainee.nontax.dao.UserMapper;
import com.bosssoft.trainee.nontax.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sct
 * @since 2022-06-15
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    @Override
    public UserPO findUserByUserName(String username) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        //执行查询
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 分页查询用户信息
     * @param page
     * @param userDTO
     * @return
     */
    @Override
    public IPage<UserPO> findUserListByPage(IPage<UserPO> page, UserDTO userDTO) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        //部门编号
        queryWrapper.eq(!ObjectUtils.isEmpty(userDTO.getDepartmentId()),"department_id",userDTO.getDepartmentId());
        //用户名
        queryWrapper.like(!ObjectUtils.isEmpty(userDTO.getUsername()),"username",userDTO.getUsername());
        //真实姓名
        queryWrapper.like(!ObjectUtils.isEmpty(userDTO.getRealName()),"real_name",userDTO.getRealName());
        //电话
        queryWrapper.like(!ObjectUtils.isEmpty(userDTO.getPhone()),"phone",userDTO.getPhone());
        return baseMapper.selectPage(page,queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteById(Long id) {
        UserPO userPO = baseMapper.selectById(id);
        baseMapper.deleteUserRole(id);
        return baseMapper.deleteById(id) > 0&& userPO != null;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        baseMapper.deleteUserRole(userId);
        return baseMapper.saveUserRole(userId,roleIds)>0;
    }
}
